import { join } from 'node:path'
import process from 'node:process'
import { electronApp, is, optimizer } from '@electron-toolkit/utils'

import { app, BrowserWindow, shell } from 'electron'
import icon from '../../resources/icon.png?asset'
import { getUnifiedBookingService } from './booking/booking-service'
import { loadConfig } from './config/index'
import { closeDatabase, initializeDatabase } from './db/index'
import { setupIpcHandlers } from './ipc/index'
import { setupLogger } from './logger/index'
import './resolve-shim'

function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: true,
      nodeIntegration: false,
    },
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  // 开发环境可通过环境变量控制是否自动打开 DevTools
  const shouldAutoOpenDevtools = is.dev
    && ['1', 'true', 'yes'].includes(String(process.env.AUTO_OPEN_DEVTOOLS || '').toLowerCase())

  if (shouldAutoOpenDevtools) {
    mainWindow.webContents.openDevTools({ mode: 'detach' })
  }

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env.ELECTRON_RENDERER_URL) {
    mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL)
  }
  else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
  try {
    const { app: electronAppInstance } = await import('electron')
    // Force userData path to %APPDATA%/AutoTools for consistent logs/data location
    electronAppInstance.setPath('userData', join(electronAppInstance.getPath('appData'), 'AutoTools'))
  }
  catch {}
  // 生产环境禁用 GPU，以降低驱动相关的不稳定
  if (!is.dev) {
    try {
      app.disableHardwareAcceleration()
      app.commandLine.appendSwitch('disable-gpu')
      app.commandLine.appendSwitch('disable-software-rasterizer')
    }
    catch {}
  }

  // 模块解析修补已在 resolve-shim 中统一安装
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.autotools.appointment')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  try {
    await loadConfig()
    await setupLogger()
    const db = await initializeDatabase()
    try {
      const { bootstrapDatabaseIfNeeded } = await import('../main/db/bootstrap')
      await bootstrapDatabaseIfNeeded(db as any)
    }
    catch {}
    setupIpcHandlers()
  }
  catch (e) {
    console.error('应用初始化失败', e)
  }

  createWindow()

  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0)
      createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 应用关闭前的清理工作
app.on('before-quit', async (event) => {
  // 阻止默认退出行为，等待清理完成
  event.preventDefault()

  try {
    // 清理多进程预约服务
    const bookingService = getUnifiedBookingService()
    await bookingService.shutdown()
  }
  catch (error) {
    console.error('清理多进程预约服务失败:', error)
  }

  try {
    // 关闭数据库连接
    await closeDatabase()
  }
  catch (error) {
    console.error('关闭数据库连接失败:', error)
  }

  // 清理完成后退出应用
  app.exit(0)
})
